package com.pjc.rpc.pool;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.thrift.transport.TSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Thrift客户端类
 * 
 * @author 王畅
 * @version 创建时间：2015-6-16 上午09:24:57
 */
public class ThriftScoketProvider {
	private static final Logger log = LoggerFactory.getLogger(ThriftScoketProvider.class);

	private int minIdle = 5;

	private boolean testOnBorrow = true;
	private boolean testOnReturn = true;
	private boolean testWhileIdle = true;

	private GenericObjectPool<TSocket> poolObject;

	public ThriftScoketProvider() {
	}

	public void init(ThriftPoolObjectFacory poolFactory, int maxTotal, int maxIdle) {
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		config.setMaxIdle(maxIdle);
		config.setMaxTotal(maxTotal);
		config.setMaxIdle(this.minIdle);
		config.setTestOnBorrow(this.testOnBorrow);
		config.setTestOnReturn(this.testOnReturn);
		config.setTestWhileIdle(this.testWhileIdle);
		poolObject = new GenericObjectPool<TSocket>(poolFactory, config);

	}

	public TSocket getConnection() throws Exception {
		TSocket socket = poolObject.borrowObject();
		return socket;

	}

	public void returnConn(TSocket socket) {
		poolObject.returnObject(socket);
	}

	public void closePool() {
		poolObject.close();
	}

	/**
	 * 销毁通过borrowObject获取的连接对象
	 * 
	 * @param socket
	 */
	public void invalidate(TSocket socket) {
		try {
			poolObject.invalidateObject(socket);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

	}
}
